﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace UVMComm
{
    class kjCli
    {
        #region ConnectEventArgs Class
        public class ConnectEventArgs
        {
            public ConnectEventArgs(string IPADDR, int PORT)
            {
                IpAddr = IPADDR;
                Port = PORT;
            }
            private string ipAddr;
            public string IpAddr
            {
                get { return ipAddr; }
                set { ipAddr = value; }
            }
            private int port;
            public int Port
            {
                get { return port; }
                set { port = value; }
            }
        };
        public class ConnectTryingEventArgs : ConnectEventArgs
        {
            private int tryNo;

            public int TryNo
            {
                get { return tryNo; }
                set { tryNo = value; }
            }

            public ConnectTryingEventArgs(string IPADDR, int PORT, int TRYNO)
                : base(IPADDR, PORT)
            {
                TryNo = TRYNO;
            }

        };
        #endregion

        #region Declare Delegate
        public delegate void ConnectFail(ConnectEventArgs e);
        public delegate void ConnectSucc(ConnectEventArgs e);
        public delegate void ConnectTrying(ConnectTryingEventArgs e);
        public delegate void RecieveFail();
        #endregion

        #region PrivateMember and Property
        private Socket dataSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        protected Socket DataSock
        {
            get { return dataSock; }
            set { dataSock = value; }
        }
        private const int ReceiveBufSize = 65535;
        #endregion

        #region Declare Event
        public event ConnectFail ConFail;
        public event ConnectSucc ConSucc;
        public event ConnectTrying ConTry;
        public event RecieveFail RecvFail;
        #endregion

        #region ConnectMethods
        public bool Connect(string IPAddr, int Port, int ConnectTryNum)
        {
            if (!ConnectTry(IPAddr, Port, ConnectTryNum))
            {
                if (ConFail != null)
                    ConFail(new ConnectEventArgs(IPAddr, Port));
                return false;
            }
            else
            {
                if (ConSucc != null)
                    ConSucc(new ConnectEventArgs(IPAddr, Port));
                return true;
            }
        }
        private bool ConnectTry(string IPAddr, int Port, int tryNo)
        {
            bool isCon = false;
            for (int i = 0; i < tryNo; i++)
            {
                if(ConTry != null)
                    ConTry(new ConnectTryingEventArgs(IPAddr, Port, i));
                
                // 예외 삼키기
                try
                {
                    DataSock.Connect(IPAddress.Parse(IPAddr), Port);
                    isCon = true;
                    break;
                }
                catch (Exception)
                {
                    isCon = false;
                }
            }
            return isCon;
        }
        #endregion

        #region CloseMethods
        public void Close()
        {
            DataSock.Close();
        }
        #endregion

        #region SendMethod
        public bool SendPacket(Packet pc)
        {
            return SendBytes(pc.GetBytes());
        }
        private bool SendBytes(byte[] buf)
        {
            try
            {
                DataSock.Send(buf);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
	    #endregion

        #region RecieveMethod
        public Packet RecievePacket()
        {
            byte[] receivebuf = new byte[ReceiveBufSize];
            int RecieveSize = RecieveBytes(ref receivebuf);

            if (RecieveSize <= 0 || RecvFail != null)
            {
                RecvFail();
                return null;
            }

            List<byte> retPacketbyte = new List<byte>();
            for(int i=0; i < RecieveSize; i++)
                retPacketbyte.Add(receivebuf[i]);

            return new Packet(retPacketbyte.ToArray());
        }
        private int RecieveBytes(ref byte[] buf)
        {
            try
            {
                DataSock.ReceiveTimeout = 500;
                return DataSock.Receive(buf);
            }
            catch (Exception)
            {
                return -1;
            }
        }
    	#endregion 
    };
}